<template>
  <div style="padding: 10px">
    <el-card>
      <el-form
        ref="workOrderForm"
        :model="proWorkAllVo"
        :rules="rules"
        label-position="right"
        size="medium"
        label-width="100px"
        class="form-style"
      >
        <el-form-item label="产品" prop="pkProProduct">
          <el-select
            v-model="proWorkAllVo.pkProProduct"
            placeholder="请选择产品"
            style="width: 100%"
            clearable
            filterable
            @clear="tableData = []"
            @change="selectProduct"
          >
            <el-option
              v-for="(item, index) in productList"
              :key="item.pkProProduct"
              :label="item.productName"
              :value="item.pkProProduct"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="workAddTime">
          <el-date-picker
            type="datetime"
            placeholder="选择日期"
            v-model="proWorkAllVo.workAddTime"
            style="width: 100%"
            disabled
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="数量" prop="wrokNum">
          <el-input-number
            v-model.number="proWorkAllVo.wrokNum"
            :min="1"
            :precision="2"
            label="请输入工单数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="工单编号" prop="wrokId">
          <el-input
            v-model="proWorkAllVo.wrokId"
            placeholder="请输入工单编号"
            disabled
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select
            filterable
            clearable
            v-model="proWorkAllVo.unit"
            placeholder="请选择单位"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报工顺序" prop="workOrder">
          <el-select
            filterable
            clearable
            v-model="proWorkAllVo.workOrder"
            placeholder="请选择报工顺序"
          >
            <el-option
              v-for="item in workOrderList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注 " prop="workRemark">
          <el-input
            v-model="proWorkAllVo.workRemark"
            type="textarea"
            placeholder="请输入备注 "
            autosize
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header" class="clearfix">
        <el-tag
          size="medium"
          :type="proWorkAllVo.productName ? 'success' : 'danger'"
          >{{
            proWorkAllVo.productName ? proWorkAllVo.productName : "请选择产品"
          }}</el-tag
        >
      </div>
      <el-table :data="tableData" border v-loading="tableLoading">
        <template slot="empty">
          <div style="font-size: 14px; color: #999">暂无数据,请先选择产品</div>
        </template>
        <el-table-column type="index" :index="1" label="序号" align="center">
        </el-table-column>
        <el-table-column prop="craftName" label="工序" align="center">
          <template slot-scope="scope">
            <el-input
              disabled
              v-model="scope.row.craftName"
              placeholder="请输入工序名称"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="craftPriceTime"
          label="计时单价(元)"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number
              size="small"
              disabled
              v-model="scope.row.craftPriceTime"
              :precision="3"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="craftPriceNum"
          label="计件单价(元)"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number
              size="small"
              disabled
              v-model="scope.row.craftPriceNum"
              :precision="3"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="userIds" label="参与员工" align="center">
          <template slot-scope="scope">
            <el-select
              v-if="userChangeShow"
              v-model="scope.row.userIds"
              placeholder="请选择参与员工"
              style="width: 100%"
              multiple
              @change="userChange"
            >
              <el-option
                v-for="(item, index) in staffList"
                :key="item.userId"
                :label="item.nickName"
                :value="String(item.userId)"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="payProject" label="结算方式" align="center">
          <template slot-scope="scope">
            <el-select
              v-if="payFunShow"
              v-model="scope.row.payProject"
              placeholder="请选择结算方式"
              style="width: 100%"
              clearable
              @change="selectSettlement"
            >
              <el-option
                v-for="item in settlementList"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <!--                <el-button @click="" type="text" size="small">编辑</el-button>-->
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="handleClickDel(scope.$index, scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; display: flex; justify-content: center">
        <el-button
          type="primary"
          :loading="publicLoading"
          :disabled="publicLoading"
          @click="publish"
          >保存并发布</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAllProductListApi } from "@/api/product/product.js";
import { listData } from "@/api/system/dict/data";
import { addWorkOrder, getBusinessWordIdApi } from "@/api/workOrder/workOrder";
import { getUnitListAllApi } from "@/api/product/product.js";
import { getAllListUserApi } from "@/api/salary/salary";

export default {
  components: {},
  data() {
    return {
      productList: [],
      tableLoading: false,
      tableData: [],
      userChangeShow: true,
      payFunShow: true,
      rules: {
        pkProProduct: [
          { required: true, message: "请选择产品", trigger: "change" },
        ],
        workAddTime: [
          {
            type: "date",
            required: true,
            message: "请选择工单发布时间",
            trigger: "change",
          },
        ],
        wrokNum: [
          { required: true, message: "请输入任务数量", trigger: "blur" },
        ],
        wrokId: [
          { required: true, message: "请输入工单编号", trigger: "blur" },
        ],
        workOrder: [
          { required: true, message: "请选择报工顺序", trigger: "change" },
        ],
        unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
      },
      settlementList: [],
      proWorkAllVo: {
        productName: "", // 产品名称
        pkProProduct: "", // 产品主键
        unit: "", // 单位
        workAddTime: "", // 工单发布时间
        workRemark: "", // 备注
        workOrder: 2,
        wrokId: "", // 工单编号
        wrokNum: null, // 数量
        addStatus: 0, // 发布状态 0未发布 1已发布
        // pkProWork: '', // 工单主键
        proStatus: 1, // 生产状态 1.生产中 2已完成
        proWorkCrafts: [], // 功序列表
      },
      unitList: [], // 单位列表
      staffList: [], // 员工列表
      publicLoading: false,
      workOrderList: [
        {
          id: 1,
          name: "严格顺序",
          value: 1,
        },
        {
          id: 2,
          name: "任意顺序",
          value: 2,
        },
      ], //报工顺序
    };
  },
  created() {
    // 设置发布时间为页面打开时间
    this.proWorkAllVo.workAddTime = Number(new Date());
    this.getBusinessWordId();
    // this.setWorkId();
    this.getProductList();
    this.getSettlementList();
    this.getUnitListList();
    this.getAllStaffList();
  },
  methods: {
    // 获取产品列表
    async getProductList() {
      const res = await getAllProductListApi();
      this.productList = res.data;
    },
    // 获取单位列表
    async getUnitListList() {
      const res = await getUnitListAllApi();
      this.unitList = res.data;
    },
    // 获取所有员工列表
    async getAllStaffList() {
      const res = await getAllListUserApi();
      this.staffList = res;
      // console.log(this.staffList)
    },
    // 获取结算方式列表
    getSettlementList() {
      listData({ dictType: "pro_pay_project" }).then((response) => {
        this.settlementList = response.rows;
      });
    },
    // 创建工单编号
    setWorkId() {
      let year = String(new Date().getFullYear());
      let month = String(new Date().getMonth() + 1);
      let day = String(new Date().getDate());
      let hour = String(new Date().getHours());
      let minute = String(new Date().getMinutes());
      let second = String(new Date().getSeconds());
      if (month.length === 1) {
        month = "0" + month;
      }
      if (day.length === 1) {
        day = "0" + day;
      }
      if (hour.length === 1) {
        hour = "0" + hour;
      }
      if (minute.length === 1) {
        minute = "0" + minute;
      }
      if (second.length === 1) {
        second = "0" + second;
      }
      this.proWorkAllVo.wrokId =
        "GD" + year + month + day + hour + minute + second;
    },
    // 获取工单编号
    async getBusinessWordId() {
      const { data: res } = await getBusinessWordIdApi();
      this.proWorkAllVo.wrokId = res;
    },
    // 选择产品
    async selectProduct(e) {
      // console.log(e);
      this.tableLoading = true;
      if (e) {
        const res = await getAllProductListApi({
          pkProProduct: this.proWorkAllVo.pkProProduct,
        });
        // console.log(res);
        this.tableLoading = false;
        this.proWorkAllVo.productName = res.data[0].productName;
        this.proWorkAllVo.unit = res.data[0].unit;
        this.tableData = res.data[0].productCraftList;
        this.tableData.forEach((key1) => {
          // 默认所有的所有的结算方式为：计件 -- 1
          key1.payProject = "1";
          key1.userIds = [];
          key1.proCraftUsers.forEach((key2) => {
            key1.userIds.push(key2.userId);
          });
        });
      } else {
        this.tableLoading = false;
      }
    },
    //修改参与员工
    async userChange(e) {
      this.userChangeShow = false;
      this.$nextTick(() => {
        this.userChangeShow = true;
      });
    },
    // 选择结算方式
    async selectSettlement(e) {
      // console.log(e);
      this.payFunShow = false;
      this.$nextTick(() => {
        this.payFunShow = true;
      });
      // console.log(this.tableData);
    },
    // 删除当前行工序
    async handleClickDel(index, item) {
      this.$confirm("是否确认删除当前工序?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    // 添加工序
    addProductionProcesses() {
      let newRow = {
        craftName: "", // 工序名称
        craftOrder: "", // 工序顺序
        craftPriceNum: "", // 计件单价
        craftPriceTime: "", // 计时单价
        noPassNum: 0, // 不良品数量
        passNum: 0, // 良品数量
        payProject: "", // 结算方式 1 计件 2计时
        pkCraftInfo: "", // 工序主键
        proWorkCraftUsers: [
          {
            // 工序参与员工列表
            pkCraftInfo: "", // 工序主键
            userId: "", // 员工主键
          },
        ],
        projectNum: 0, // 所需生产总数量
        status: "", // 状态 1.未开始 2进行中 3.已完成
        unit: "", // 单位
      };
      this.tableData.push(newRow);
    },
    // 设置数据
    async setData() {
      let productionProcessesList = [];
      this.tableData.forEach((ppKey, index) => {
        // console.log(ppKey);
        ppKey.craftOrder = index + 1;
        let ppItem = {
          craftName: ppKey.craftName,
          craftOrder: ppKey.craftOrder,
          craftPriceNum: ppKey.craftPriceNum,
          craftPriceTime: ppKey.craftPriceTime,
          noPassNum: 0,
          passNum: 0,
          payProject: ppKey.payProject,
          pkCraftInfo: ppKey.pkCraftInfo,
          projectNum: this.proWorkAllVo.wrokNum,
          proWorkCraftUsers: [],
          status: "",
        };
        // 任意顺序工序状态状态全部都为进行中
        // console.log("报工顺序", this.proWorkAllVo.workOrder);
        if (this.proWorkAllVo.workOrder === 2) {
          ppItem.status = "2";
        } else {
          if (ppKey.craftOrder == "1") {
            ppItem.status = "2";
          } else {
            ppItem.status = "1";
          }
        }
        ppKey.userIds.forEach((userIdKey) => {
          this.staffList.forEach((staffKey) => {
            if (userIdKey == staffKey.userId) {
              let staffItem = {
                pkCraftInfo: ppKey.pkCraftInfo,
                userId: staffKey.userId,
              };
              ppItem.proWorkCraftUsers.push(staffItem);
            }
          });
        });
        productionProcessesList.push(ppItem);
      });
      // console.log(productionProcessesList);
      this.proWorkAllVo.proWorkCrafts = productionProcessesList;
      // console.log("提交参数", this.proWorkAllVo);
    },
    // 判断是否有员工
    getIsUserId() {
      // console.log(this.proWorkAllVo.proWorkCrafts, "proWorkAllVo");
      const { proWorkCrafts } = this.proWorkAllVo;
      let hasEmptyUser = false;
      for (let i = 0; i < proWorkCrafts.length; i++) {
        const element = proWorkCrafts[i].proWorkCraftUsers;
        // console.log(element, "element");
        if (element.length === 0) {
          hasEmptyUser = true;
          // console.log("没有参与员工");
          break; // 跳出循环
        }
      }
      if (hasEmptyUser) {
        return false;
      } else {
        console.log("有参与员工");
        return true;
      }
    },
    // 发布工单
    async publish() {
      await this.$refs["workOrderForm"].validate((valid) => {
        if (!valid) return;
        this.proWorkAllVo.workAddTime = Number(new Date());
        this.setData();
        // userIds
        const isUserId = this.getIsUserId();
        if (!isUserId) {
          this.$message.error("请选择参与员工或删除本次不涉及的工序!");
          return;
        }
        this.publicLoading = true;
        addWorkOrder(this.proWorkAllVo)
          .then((res) => {
            // console.log(res);
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.$refs["workOrderForm"].resetFields();
              this.tableData = [];
              // 设置发布时间为页面打开时间
              this.proWorkAllVo.workAddTime = Number(new Date());
              this.getBusinessWordId();
              // this.setWorkId();
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((error) => {})
          .finally(() => {
            this.publicLoading = false;
          });
      });
    },
  },
};
</script>

<style>
.form-style {
  display: flex;
  flex-wrap: wrap;
}
.el-form-item {
  margin-bottom: 10px;
}
</style>
